# -*- coding: utf-8 -*-

import re

from debug import debug

NOPIPE = r'[^\|]*'
LOGLINE_RE = (r'(\d{4})(\d{2})(\d{2})\|(\d{2})(\d{2})\|(' + NOPIPE + r')\|' +
    NOPIPE + r'\|' + NOPIPE + r'\|(' + NOPIPE + r')\|(.*)')
KEY_RE = r'([^\[\]])|\[KeyName:(\[?[^\[\]]+\]?)\]'
browser_list = ['Navigator', 'google-chrome', 'firefox', 'iceweasel',
                'chromium-browser']
website_list = ['Gmail', 'YouTube','Facebook', 'Yahoo!', 'Wikipedia',
                'Wikipédia', 'Twitter', '/b/', 'reddit', 'Slashdot',
                'Google Reader', 'Python', 'Google Search', 'Stack Overflow']


class Parser:
    '''Parses log lines and sends Python objects to the stats aggregator'''
    def __init__(self, statsaggregator):
        self.sa = statsaggregator
        self.linepattern = re.compile(LOGLINE_RE, re.UNICODE)
        self.keypattern = re.compile(KEY_RE, re.UNICODE)
        debug('StatsAggregator OK')
        return


    def on_log_line(self, string):
        #debug('processing string:')

        g = self.linepattern.match(string)
        if not g:
            print 'Failed to parse the line'
            return
        g = g.groups()
        if len(g) != 8:
            print 'Failed to parse the line'
            return
        event = {}
        event['year']       = g[0]
        event['month']      = g[1]
        event['day']        = g[2]
        event['hour']       = g[3]
        event['minute']     = g[4]
        event['process']    = g[5]
        event['title']      = g[6]
        event['keycount']   = {}
        event['website']    = ''
        keys_matched = self.keypattern.findall(g[7])
        for k in keys_matched:
            if k[0]:
                try:
                    event['keycount'][k[0]] += 1    # normal characters
                except KeyError:
                    event['keycount'][k[0]] = 1
            elif k[1]:
                try:
                    event['keycount'][k[1]] += 1    # special characters
                except:
                    event['keycount'][k[1]] = 1
            else:
                debug('Could not find a character...')
       # debug(event['keycount'])
        self.get_website_name(event)
        self.get_terminal_app(event)
        self.sa.on_process_event(event)
        return

    def get_website_name(self, event):
        if not event['title']:
            return

        if event['process'] in browser_list:
            for w in website_list:
                if w in event['title']:
                    event['website']=w
                    break

            if not event['website']:
               event['website'] ='Other'
        return

    def get_terminal_app(self, event):
        if event['process'] == 'gnome-terminal' and 'VIM' in event['title']:
            event['process'] = 'VIM'
        return

